<script setup lang="ts">
import { onMounted, ref, computed } from 'vue';
import { RequestPath, startRequest } from '../base/RequestWork';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import Account from '../base/AccountStore';

// 订单数据
let order = ref()
// 评价内容数组，对应每个商品
let contents = ref<string[]>([])
// 评分数组，对应每个商品
let stars = ref<number[]>([])
let router = useRouter()
let route = useRoute()
let account = Account()

// 计算属性：检查是否所有商品都已评价
const isAllEvaluated = computed(() => {
    if (!order.value || !order.value.goods) return false
    
    for (let i = 0; i < order.value.goods.length; i++) {
        if (stars.value[i] === 0 || !contents.value[i] || contents.value[i].trim().length === 0) {
            return false
        }
    }
    return true
})

// 计算属性：提交按钮文本
const submitButtonText = computed(() => {
    return isAllEvaluated.value ? '提交评价' : '请完成所有评价'
})

// 组件加载时请求订单数据
onMounted(()=>{
    // 检查是否登录
    if (!account.isLogin) {
        ElMessage.warning('请先登录后再进行评价')
        router.push({
            name: 'login'
        })
        return
    }
    
    let orderId = route.params.order
    console.log('订单ID:', orderId)
    
    // 获取订单列表
    startRequest(RequestPath.orderListGet, 'get', {
        type: 1,
        limit: 100,
        offset: 0
    }).then((response)=>{
        console.log('完整响应:', response)
        
        let orders = []
        // 尝试多种可能的数据结构
        if (response.data && response.data.data && response.data.data.orders) {
            orders = response.data.data.orders
        } else if (response.data && response.data.datas) {
            orders = response.data.datas
        } else if (response.data && Array.isArray(response.data)) {
            orders = response.data
        } else if (response.data && response.data.data && Array.isArray(response.data.data)) {
            orders = response.data.data
        }
        
        console.log('解析出的订单列表:', orders)
        
        // 将orderId转换为数字进行比较
        const numericOrderId = Number(orderId)
        order.value = orders.find((item: any) => item.id === numericOrderId)
        console.log('找到的订单:', order.value)
        
        if (order.value && order.value.goods) {
            // 初始化评价数组
            contents.value = new Array(order.value.goods.length).fill('')
            stars.value = new Array(order.value.goods.length).fill(0)
        }
        
        if (!order.value) {
            ElMessage.error('未找到对应的订单，订单ID: ' + orderId)
            console.log('所有可用订单ID:', orders.map((item: any) => item.id))
        }
    }).catch((error)=>{
        console.error('加载订单错误:', error)
        ElMessage.error({
            message: error.response?.data?.error || '加载订单数据失败'
        })
    }) 
})

// 提交评价
function submitEvaluation() {
    if (!isAllEvaluated.value) {
        ElMessage.error({
            message: "请为所有商品选择评分并填写评价内容"
        })
        return
    }
    
    if (!order.value || !order.value.goods || order.value.goods.length === 0) {
        ElMessage.error('订单数据不完整')
        return
    }
    
    let orderId = route.params.order
    
    // 构建评价数据数组，每个商品一个评价
    const evaluations = order.value.goods.map((goodsItem: any, index: number) => ({
        gid: goodsItem.item.id,
        content: contents.value[index],
        star: stars.value[index]
    }))
    
    console.log('提交的评价数据:', evaluations)
    
    // 将oid作为查询参数传递，评价数据作为请求体
    startRequest(`${RequestPath.evaluationCreate}?oid=${orderId}`, 'post', evaluations).then((response)=>{
        if (response.data.msg != 'ok') {
            ElMessage.error({
                message: response.data.error || '评价提交失败'
            })
        } else {
            ElMessage.success({
                message: "评价成功！感谢您的评价"
            })
            // 跳转回订单页面
            router.push({
                name: 'order'
            })
        }
    }).catch((error)=>{
        ElMessage.error({
            message: error.response?.data?.error || '评价提交失败'
        })
    })
}

// 单个商品的评价是否完成
    function isGoodsEvaluated(index: number): boolean {
        return stars.value[index] > 0 && 
               typeof contents.value[index] === 'string' && 
               contents.value[index].trim().length > 0
    }
</script>

<template>
    <div class="evaluation-container">
        <!-- 评价页面头部 -->
        <div class="title">订单商品评价</div>
        <div class="sub-title">请对订单中的每个商品进行评价</div>
        
        <!-- 订单信息 -->
        <div class="order-info" v-if="order">
            <div class="order-header">
                <span class="order-id">订单编号：{{ order.id }}</span>
                <span class="order-date">下单时间：{{ order.created_at }}</span>
            </div>
        </div>

        <!-- 商品评价列表 -->
        <div class="goods-evaluation-list" v-if="order && order.goods && order.goods.length > 0">
            <div class="goods-evaluation-item" 
                 v-for="(goodsItem, index) in order.goods" 
                 :key="goodsItem.item.id"
                 :class="{ 'evaluated': isGoodsEvaluated(index) }">
                
                <!-- 商品信息 -->
                <div class="goods-info">
                    <div class="goods-image">
                        <el-image 
                            style="width: 120px; height: 120px;" 
                            :src="goodsItem.item.image" 
                            fit="cover"
                            :preview-src-list="[goodsItem.item.image]"
                        />
                    </div>
                    <div class="goods-details">
                        <div class="goods-name">{{ goodsItem.item.name }}</div>
                        <div class="goods-description">{{ goodsItem.item.description }}</div>
                        <div class="goods-price">￥{{ goodsItem.item.discounted_price }}</div>
                        <div class="goods-count">购买数量：{{ goodsItem.count }}件</div>
                    </div>
                </div>

                <!-- 评价区域 -->
                <div class="evaluation-area">
                    <div class="evaluation-section">
                        <div class="section-title">请选择评分：</div>
                        <el-rate 
                            v-model="stars[index]" 
                            show-score 
                            text-color="#ff9900" 
                            score-template="{value} 分"
                            class="rating-stars"
                        />
                    </div>
                    
                    <div class="evaluation-section">
                        <div class="section-title">请填写评价内容：</div>
                        <el-input
                            v-model="contents[index]"
                            :rows="4"
                            type="textarea"
                            placeholder="请分享您对这款商品的使用感受，您的评价对其他用户很有帮助"
                            maxlength="500"
                            show-word-limit
                            class="evaluation-textarea"
                        />
                    </div>

                    <!-- 评价状态提示 -->
                    <div class="evaluation-status" v-if="isGoodsEvaluated(index)">
                        <el-icon color="#67C23A"><CircleCheck /></el-icon>
                        <span>已评价</span>
                    </div>
                </div>
                
                <div class="divider"></div>
            </div>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-section" v-if="order && order.goods && order.goods.length > 0">
            <div class="submit-tips">
                <el-icon><InfoFilled /></el-icon>
                请确保为所有商品完成评价后再提交
            </div>
            <el-button 
                type="primary" 
                size="large" 
                @click="submitEvaluation"
                :disabled="!isAllEvaluated"
                class="submit-button"
            >
                {{ submitButtonText }}
            </el-button>
        </div>

        <!-- 空状态 -->
        <div v-else-if="order" class="loading">
            订单数据加载中...
        </div>
        <div v-else class="error">
            未找到订单信息或订单数据不完整
        </div>
    </div>
</template>

<style scoped>
.evaluation-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.title {
    font-size: 24px;
    margin-bottom: 8px;
    font-weight: 900;
    color: #333;
}

.sub-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 24px;
}

.order-info {
    background: #f5f7fa;
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 24px;
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.order-id {
    font-weight: 600;
    color: #333;
}

.order-date {
    color: #666;
    font-size: 14px;
}

.goods-evaluation-list {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.goods-evaluation-item {
    padding: 24px;
    transition: all 0.3s ease;
}

.goods-evaluation-item.evaluated {
    background: #f0f9ff;
    border-left: 4px solid #409eff;
}

.goods-evaluation-item:not(:last-child) {
    border-bottom: 1px solid #e4e7ed;
}

.goods-info {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
}

.goods-image {
    flex-shrink: 0;
}

.goods-image .el-image {
    border-radius: 8px;
    border: 1px solid #e4e7ed;
}

.goods-details {
    flex: 1;
}

.goods-name {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
}

.goods-description {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
    line-height: 1.4;
}

.goods-price {
    font-size: 16px;
    color: #e02020;
    font-weight: 600;
    margin-bottom: 4px;
}

.goods-count {
    font-size: 14px;
    color: #999;
}

.evaluation-area {
    padding-left: 136px; /* 对齐商品信息内容 */
}

.evaluation-section {
    margin-bottom: 20px;
}

.section-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 8px;
    font-weight: 500;
}

.rating-stars {
    margin-bottom: 8px;
}

.evaluation-textarea {
    width: 100%;
}

.evaluation-status {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #67C23A;
    font-size: 14px;
    margin-top: 12px;
}

.divider {
    height: 1px;
    background: #f0f0f0;
    margin: 16px 0;
}

.goods-evaluation-item:last-child .divider {
    display: none;
}

.submit-section {
    margin-top: 32px;
    text-align: center;
    padding: 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.submit-tips {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: #606266;
    margin-bottom: 16px;
    font-size: 14px;
}

.submit-button {
    width: 200px;
    height: 44px;
    font-size: 16px;
}

.loading, .error {
    text-align: center;
    padding: 50px;
    font-size: 18px;
    color: #666;
}

.error {
    color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .evaluation-container {
        padding: 16px;
    }
    
    .goods-info {
        flex-direction: column;
    }
    
    .goods-image {
        align-self: center;
    }
    
    .evaluation-area {
        padding-left: 0;
    }
    
    .order-header {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
    }
}
</style>